import 'dart:typed_data';
import 'dart:ui' as ui;
import 'package:animation_effect_demo/src/effects/base/base_effect.dart';
import 'package:image/image.dart' as img;
import 'package:flutter/material.dart';

import 'dart:ui' as ui;




class TextDataInfo {
  Uint8List data;
  int width;
  int height;

  TextDataInfo(this.data, this.width, this.height);
}

abstract class BaseTextAnimationEffect implements BaseEffect {
  TextPainter getTextPainter(
      {required String text,
      required Color color,
      required double fontSize,
      String? fontFamily}) {
    final children = <TextSpan>[];
    final runes = text.runes;

    for (int i = 0; i < runes.length; /* empty */) {
      int current = runes.elementAt(i);

      final isEmoji = current > 255;
      final shouldBreak = isEmoji ? (x) => x <= 255 : (x) => x > 255;

      final chunk = <int>[];
      while (!shouldBreak(current)) {
        chunk.add(current);
        if (++i >= runes.length) break;
        current = runes.elementAt(i);
      }

      children.add(
        TextSpan(
          text: String.fromCharCodes(chunk),
        ),
      );
    }

    final fontPaint = Paint()..color = color..isAntiAlias = false;
    TextSpan textSpan = TextSpan(
      children: children,
      style: TextStyle(
          fontSize: fontSize,
          fontFamily: fontFamily??'HeiTi',
          foreground: fontPaint,
        // color: color,
        // package: 'text_diy'
      ),
    );

    return TextPainter(
      text: textSpan,
      textDirection: TextDirection.ltr,
    )..layout(maxWidth: 200);
  }

  Future<TextDataInfo> getTextData(
      {required String text,
      required Color color,
      required double fontSize,
      String? fontFamily}) async {
    var textPainter = getTextPainter(
      text: text,
      color: color,
      fontSize: fontSize,
      fontFamily: fontFamily,
    );

    ui.PictureRecorder recorder = ui.PictureRecorder();

    ///获取文本绘画范围
    var textSize = textPainter.size;
    var canvas = Canvas(
        recorder,
        Rect.fromPoints(
            const Offset(0, 0), Offset(textSize.width, textSize.height)));
    textPainter.paint(canvas, Offset.zero);
    var picture = recorder.endRecording();

    int imageWidth = textSize.width.round();
    int imageHeight = textSize.height.round();
    var image = await picture.toImage(imageWidth, imageHeight);
    ByteData byteData = (await image.toByteData(format: ui.ImageByteFormat.png))!;
    // Uint8List pngBytes = byteData.buffer.asUint8List();
    // final textImg = img.decodeImage(pngBytes)!;
    // final newImg = img.copyResize(textImg, width: imageWidth~/1.5,height: imageHeight~/1.5);
    // return TextDataInfo(newImg.buffer.asUint8List(), newImg.width, newImg.height);
    return TextDataInfo(byteData.buffer.asUint8List(), imageWidth, imageHeight);
  }
}
